import * as math from "mathjs";
import store from "@/store";
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'
var timer=null
export default {
  // 时间戳转年月日
  timestampTime(timestamp) {
    var date = new Date(timestamp); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    const Y = date.getFullYear() + "-";
    const M =
      (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
    const D = date.getDate() + " ";
    const h = date.getHours() + ":";
    const m =
      date.getMinutes() < 10
      ? "0" + date.getMinutes() + ":"
      : date.getMinutes() + ":";
    const s =
      date.getSeconds() < 10
      ? "0" + date.getSeconds()
      : date.getSeconds();
    return Y + M + D + h + m + s;
  },
  // 年月日转时间戳
  timeTimestamp(date) {
    const timestamp = new Date(date).getTime();
    return timestamp;
  },
  // 时间转换[时间字符串切割显示时间]
  timeTurn(date) {
    let time1=date.substring(0,10),time2=date.substring(11,19)
    date=time1+' '+time2
    return date
    // return new Date(new Date(date).getTime() + 8 * 3600 * 1000).toJSON().substring(0, 19).replace("T", " ");
  },
  getApiTime(dataTime, format) {
    const formateArr = ["Y", "M", "D", "h", "m", "s"];
    dataTime = dataTime || "";
    format = format || "Y-M-D h:m";
    // 使用方式
    const returnArr = [];
    let date = "";
    // 根据传入的时间转换格式
    if (
      dataTime.toString().indexOf("-") == -1 &&
      dataTime.toString().indexOf("/") == -1
    ) {
      if (dataTime.toString().length > 10) {
        date = dataTime ? new Date(dataTime) : new Date();
      } else {
        date = dataTime ? new Date(dataTime * 1000) : new Date();
      }
    } else {
      date = dataTime
      ? new Date(dataTime.replace(/-/g, "/"))
      : new Date();
    }
    returnArr.push(date.getFullYear());
    returnArr.push(this.formatNumber(date.getMonth() + 1));
    returnArr.push(this.formatNumber(date.getDate()));
    returnArr.push(this.formatNumber(date.getHours()));
    returnArr.push(this.formatNumber(date.getMinutes()));
    returnArr.push(this.formatNumber(date.getSeconds()));
    for (const i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  },
  formatNumber(n) {
    n = n.toString();
    return n[1] ? n : "0" + n;
  },
  // 0代表今日,-1代表昨日，1代表明日
  getDateDay(dates) {
    if(localStorage.getItem("serverTime")){
      var dd = new Date(localStorage.getItem("serverTime"))
    }else{
      var dd = new Date()
    }
    var n = dates || 0;
    dd.setDate(dd.getDate() + n);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    var d = dd.getDate();
    m = m < 10 ? "0" + m : m;
    d = d < 10 ? "0" + d : d;
    var day = y + "-" + m + "-" + d;
    return day;
  },
  // "s"代表开始,"e"代表结束，dates为数字类型，不传或0代表本周，-1代表上周，1代表下周
  getDateWeek(type, dates) {
    // if(!dates){
      dates=-1
    // }
    if(localStorage.getItem("serverTime")){
      var now = new Date(localStorage.getItem("serverTime"))
    }else{
      var now = new Date()
    }
    var nowTime = now.getTime();
    // var day = now.getDay();
    var day =-1;
    var longTime = 24 * 60 * 60 * 1000;
    var n = longTime * 7 * (dates || 0);
    if (type == "s") {
      var dd = nowTime - day * longTime + n;
    }
    if (type == "e") {
      var dd = nowTime + (6 - day) * longTime + n;
    }
    dd = new Date(dd);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    var d = dd.getDate();
    m = m < 10 ? "0" + m : m;
    d = d < 10 ? "0" + d : d;
    var day = y + "-" + m + "-" + d;
    return day;
    // var now = new Date(localStorage.getItem("serverTime"));
    // var nowTime = now.getTime();
    // var day = now.getDay();
    // var longTime = 24 * 60 * 60 * 1000;
    // var n = longTime * 7 * (dates || 0);
    // if (type == "s") {
    //   var dd = nowTime - day * longTime + n;
    // }
    // if (type == "e") {
    //   var dd = nowTime + (6 - day) * longTime + n;
    // }
    // dd = new Date(dd);
    // var y = dd.getFullYear();
    // var m = dd.getMonth() + 1;
    // var d = dd.getDate();
    // m = m < 10 ? "0" + m : m;
    // d = d < 10 ? "0" + d : d;
    // var day = y + "-" + m + "-" + d;
    // return day;
  },
  // 获取本月开始和结束的一天
  getDateMonth(type, months) {
    if(localStorage.getItem("serverTime")){
      var d = new Date(localStorage.getItem("serverTime"))
    }else{
      var d = new Date()
    }
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    if (Math.abs(months) > 12) {
      months = months % 12;
    }
    if (months != 0) {
      if (month + months > 12) {
        year++;
        month = (month + months) % 12;
      } else if (month + months < 1) {
        year--;
        month = 12 + month + months;
      } else {
        month = month + months;
      }
    }
    month = month < 10 ? "0" + month : month;
    var date = d.getDate();
    var firstday = year + "-" + month + "-" + "01";
    var lastday = "";
    if (
      month == "01" ||
      month == "03" ||
      month == "05" ||
      month == "07" ||
      month == "08" ||
      month == "10" ||
      month == "12"
    ) {
      lastday = year + "-" + month + "-" + 31;
    } else if (month == "02") {
      if (
        (year % 4 == 0 && year % 100 != 0) ||
        (year % 100 == 0 && year % 400 == 0)
      ) {
        lastday = year + "-" + month + "-" + 29;
      } else {
        lastday = year + "-" + month + "-" + 28;
      }
    } else {
      lastday = year + "-" + month + "-" + 30;
    }
    var day = "";
    if (type == "s") {
      day = firstday;
    } else {
      day = lastday;
    }
    return day;
  },
  // 只允许小数点后4位
  keepFour(val) {
    val = Number(val);
    return (val.toFixed(4) * 10000) / 10000;
  },
  // 四舍五入
  roundFive(val) {
    return Math.ceil(val);
  },
  // 道具回显-字符串转数组
  srtToArr(str) {
    if (str.split(";").length > 1) {
      str = str.split(";");
      str.map((v, h) => {
        str[h] = v.split(",");
      });
    } else {
      str = str.split(",");
    }
    return str;
  },
  // 标准时间--年月日
  standardDate(timestamp) {
    var date = new Date(timestamp);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    var d = date.getDate();
    d = d < 10 ? "0" + d : d;
    var h = date.getHours();
    h = h < 10 ? "0" + h : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    var s = date.getSeconds();
    s = s < 10 ? "0" + s : s;
    const time = y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + s;
    return time;
  },
  // 标准时间--年月日--服务器时间戳
  standardTime(timestamp) {
    var date = new Date(timestamp);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    var d = date.getDate();
    d = d < 10 ? "0" + d : d;
    var h = date.getHours();
    h = h < 10 ? "0" + h : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    var s = date.getSeconds();
    s = s < 10 ? "0" + s : s;
    const time = y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + s;
    return this.serverTime(Date.parse(time)); // 转为秒数
  },
  // 时间差值(优化显示)【服务器时间转本地时间】
  localTime(val) {
    val = Number(val);
    // 本地时区与零时区差的秒数;
    const seconds = new Date().getTimezoneOffset() * 60;
    const difference = val + seconds;
    return this.getApiTime(difference, "Y-M-D h:m:s");
  },
  // 时间差值(优化显示)【本地时间转服务器时间】
  serverTime(val) {
    // 本地时区与零时区差的秒数;
    const seconds = new Date().getTimezoneOffset() * 60;
    const difference = val / 1000 - seconds;
    return parseInt(difference);
  },
  // 服务器时间【 1.公共头部组件 2.获取用户信息 】
  getServerTime(val) {
    let time = new Date(val).getTime() / 1000+1,count=0;
    timer= setInterval(() => {
      time+=1
      count+=1
      if(count>=180){
        count=0
        clearInterval(timer)
        this.getTime()
      }
      localStorage.setItem("serverTime", this.timestampTime(time * 1000));
    }, 1000);
  },
  async getTime(){
    await store.dispatch('commonState/updateTimeData')
  },
  // 清空定时器
  clearIntervalTime() {
    clearInterval(timer)
    timer=null
  },
  // 服务器时间戳转本地年月日转服务器时间戳【修改时调用】
  serverLocalTime(val) {
    return this.serverTime(this.timeTimestamp(val));
  },
  // 科学计数-加
  mathNumberAddition(num1, num2) {
    const num = math.format(
      math.add(math.bignumber(num1), math.bignumber(num2))
    );
    return math.round(Number(num),4);
  },
  // 科学计数-减
  mathNumberSubtraction(num1, num2) {
    const num = math.format(
      math.subtract(math.bignumber(num1), math.bignumber(num2))
    );
    return math.round(Number(num),4);
  },
  // 科学计数-乘
  mathNumberMultiply(num1, num2) {
    const num = math.format(
      math.multiply(math.bignumber(num1), math.bignumber(num2))
    );
    return math.round(Number(num),4);
  },
  // 科学计数-除
  mathNumberDivide(num1, num2) {
    const num = math.format(
      math.divide(math.bignumber(num1), math.bignumber(num2))
    );
    return math.round(Number(num),4);
  },
  // 金额-除10000
  mathNumberDivideWan(num1) {
    const num = math.format(
      math.divide(math.bignumber(num1), math.bignumber(10000))
    );
    return math.round(Number(num),4);
  },
  // 科学计数-计算百分比
  mathNumberDividePercent(num1, num2) {
    const num = math.format(
      math.divide(math.bignumber(num1), math.bignumber(num2))
    ,4)
    const percent = math.format(
      math.multiply(math.bignumber(num), math.bignumber(100))
    );
    return Number(Number(percent).toFixed(2));
  },
  // 文档下载
  documentDownload(document) {
    window.location.href = process.env.VUE_APP_DOCUMENT + document;
  },
  // 渠道展示
  channelLabel(cellValue) {
    let dataData = store.state.commonState.channelShowDataArray;
    if (cellValue) {
      return (dataData.find((item) => item.value === cellValue)?.label || "-")
    } else {
      return "--";
    }
  },
  // 账户展示
  accountLabel(cellValue) {
    let dataData = store.state.commonState.accountDataArray;
    if (cellValue) {
      return (dataData.find((item) => item.value === cellValue)?.label ||"-")
    } else {
      return "--";
    }
  },
  // 活动的道具数量/10000
  activeNumberByWan(arr) {
    let arrData = JSON.parse(JSON.stringify(arr));
    arrData.map((item) => {
      if(item.num){
        item.num = this.mathNumberMultiply(item.num, 10000);
      }
      if(item.award){
        item.award = this.mathNumberMultiply(item.award, 10000);
      }
      if (item.condition) {
        item.condition = this.mathNumberMultiply(item.condition, 10000);
      }
    });
    return arrData;
  },
  activeNumberWan(arr) {
    arr = JSON.parse(arr);
    arr.map((item) => {
      if(item.num){
        item.num = this.mathNumberDivideWan(Number(item.num))
      }
      if(item.award){
        item.award = this.mathNumberDivideWan(Number(item.award))
      }
      if (item.condition) {
        item.condition = this.mathNumberDivideWan(
          Number(item.condition)
        );
      }
    });
    return arr;
  },
  // 转换道具【充值活动专属】
  propBack (str) {
    let arr = this.srtToArr(str), arrData = [];
    if (arr[0] && typeof (arr[0]) == 'string') {
      store.state.commonState.propDataArray.map(item=>{
        if(item.value==arr[0]){
          arrData.push({ name: item.label, num: this.mathNumberDivideWan(arr[1]) })
        }
      })
    } else {
      arr.map(item => {
        store.state.commonState.propDataArray.map(second=>{
          if(second.value==item[0]){
            arrData.push({ name: second.label, num: this.mathNumberDivideWan(item[1]) })
          }
        })
      })
    }
    return arrData
  },
  // 转换道具【充值活动专属】
  strBackArr (str) {
    let arr = this.srtToArr(str), arrData = [];
    if (arr[0] && typeof (arr[0]) == 'string') {
      arrData.push({ type: Number(arr[0]), num: this.mathNumberDivideWan(arr[1]) })
    } else {
      arr.map(item => {
        arrData.push({ type: Number(item[0]), num: this.mathNumberDivideWan(item[1]) })
      })
    }
    return arrData
  },
  // 集中处理个活动数值问题
  activeValue(item) {
    item.isChecked = false;
    // 每日首爆
    if (item.activity_type == 1) {
      if (item.other) {
        item.propData = this.activeNumberWan(item.other);
      }
    }
    // 注册送金
    if (item.activity_type == 3) {
      if (item.other) {
        item.propData = this.activeNumberWan(item.other);
      }
    }
    // 首充
    if (item.activity_type == 7) {
      // 奖励
      if(JSON.parse(item.other).reward){
        item.reward = this.activeNumberWan(JSON.stringify(JSON.parse(item.other).reward))
      }else{
        item.reward=''
      }
      // 保障金
      item.safeguard = this.activeNumberWan(
        JSON.stringify([JSON.parse(item.other).safeguard])
      );
    }
    // 拼多多
    if (item.activity_type == 9) {
      item.parameter = JSON.parse(item.other);
      for (const key in item.parameter) {
        item.parameter[key] = this.mathNumberDivideWan(
          item.parameter[key]
        );
      }
    }
    // 拼多多转盘
    if (item.activity_type == 18) {
      item.parameter = JSON.parse(item.other);
      for (const key in item.parameter) {
        if(key=='withdrawable' && key=='init_cash_min' && key=='init_cash_max' && key=='num_of_withdraw_count' && key=='num_of_receive_count'){
          item.parameter[key]=this.mathNumberDivideWan(item.parameter[key])
        }
      }
    }
    // 充值活动
    if (item.activity_type == 10) {
      item.recharge_info.forEach(second=>{
        second.reward=this.propBack(second.param)
        second.item=this.strBackArr(second.param)
      })
    }
    // 绑定有礼
    if (item.activity_type == 11) {
      item.propData = this.activeNumberWan(
        JSON.stringify(JSON.parse(item.other).reward)
      );
      item.number = JSON.parse(item.other).number;
    }
    // 下载有礼
    if (item.activity_type == 12) {
      item.propData = this.activeNumberWan(
        JSON.stringify(JSON.parse(item.other).reward)
      );
      item.number = JSON.parse(item.other).number;
      item.download = JSON.parse(item.other).download;
    }
    // 周礼包
    if (item.activity_type == 13) {
      // if(item.other){
      //   item.propData = this.propBack(JSON.stringify(JSON.parse(item.other).reward));
      //   item.reward = this.strBackArr(JSON.stringify(JSON.parse(item.other).reward));
      // }
    }
    // 七日登录
    if (item.activity_type == 15) {
      item.propData = this.activeNumberWan(
        JSON.stringify(JSON.parse(item.other).reward)
      );
      item.day = JSON.parse(item.other).day;
    }
    // 充值轮盘
    if (item.activity_type == 16) {
      item.parameter = JSON.parse(item.other);
      if(item.parameter.awards){
        item.parameter.awards.forEach(second=>{
          if(second.propItem){
            second.propItem.forEach(third=>{
              third.num=this.mathNumberDivideWan(third.num)
            })
          }
        })
      }
      item.parameter.pool_down_limit=this.mathNumberDivideWan(item.parameter.pool_down_limit,10000)
      item.parameter.pool=this.mathNumberDivideWan(item.parameter.pool,10000)
      item.parameter.time_per_recharge=this.mathNumberDivideWan(item.parameter.time_per_recharge,10000)
    }
    // 月卡
    if (item.activity_type == 17) {
      item.parameter = JSON.parse(item.other);
      item.parameter.map(item=>{
        item.soonReward=this.mathNumberDivideWan(item.soonReward,10000)
        item.reward=this.activeNumberWan(JSON.stringify(item.reward))
      })
    }
    // 代理升级
    if (item.activity_type == 19) {
      item.parameter = JSON.parse(item.other);
      if(item.parameter.awards){
        item.parameter.awards.forEach(second=>{
          second.award=this.mathNumberDivideWan(second.award)
        })
      }
    }
    return item;
  },
  // 导出excel表格
  exportTable(fileName) {
    let time=localStorage.getItem("serverTime").substring(0,11)
    var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
    var wb = XLSX.utils.table_to_book(document.querySelector('#exportTab'), xlsxParam) // #exportTab 是要导出的表格的id
    var webOut = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
    try {
      FileSaver.saveAs(new Blob([webOut], { type: 'application/octet-stream' }), fileName+time+'.xlsx')
    } catch (e) {
      if (typeof console !== 'undefined') {
        
      }
    }
    return webOut;
  },
};
export function throttle(fn, wait = 1000) {
  let timer;
  return function () {
    if (timer != null) return;
    const context = this;
    const args = arguments;
    fn.apply(context, args);
    timer = setTimeout(() => {
      timer = null;
    }, wait);
  };
}